﻿using StackExchange.Redis;
using System;
using System.Linq;
using System.Threading.Tasks;

namespace Limiting
{
    public class RedisCatchLimiting : ILimiting
    {
        private readonly IDatabase _db;
        private readonly LimitingOptions _options;

        public RedisCatchLimiting(IDatabase db, LimitingOptions options)
        {
            _db = db;
            _options = options;
        }

        public async Task<bool> CheckIdentityLimited(string identity)
        {
            if (_options.Allows.Contains(identity))
                return false;
            //把已缓存的所有时间查出来
            var items = _db
                .ListRange(identity)
                .Select(x => DateTime.Parse(x.ToString()))
                .ToList();
            items.Add(DateTime.Now);
            //算出约定时间
            var timeout = DateTime.Now.AddSeconds(-_options.Time.TotalSeconds);

            //如果访问的频率超出限制，下一步操作
            if (items.Count(x => x >= timeout) > _options.Limit)
                return true;

            //使用缓存集合 当前时间作为value
            await _db.ListRightPushAsync(identity, DateTime.Now.ToString());

            //删掉不在时间范围的item
            foreach (var item in items.Where(x => x < timeout))
            {
                _db.ListRemove(identity, item.ToString());
            }

            return false;
        }
    }
}
